package session

import (
	"time"

	"github.com/go-redis/redis"
)

type StoreRedis struct {
	client  redis.Cmdable
	expire	time.Duration
}

func NewStoreRedis(client redis.Cmdable) *StoreRedis {
	return &StoreRedis{
		client: client,
	}
}

func (r *StoreRedis) SetExpire(expire time.Duration) {
	r.expire = expire
}

func (r *StoreRedis) Get(id string, key string) interface{} {
	value := r.client.HGet(id, key).Val()
	r.client.Expire(id, r.expire)
	return value
}

func (r *StoreRedis) Set(id string, key string, value interface{}) error {
	if _, err := r.client.HSet(id, key, value).Result(); err != nil {
		return err
	}
	r.client.Expire(id, r.expire)
	return nil
}

func (r *StoreRedis) Del(id string, key string) error {
	if _, err := r.client.HDel(id, key).Result(); err != nil {
		return err
	}
	r.client.Expire(id, r.expire)
	return nil
}

func (r *StoreRedis) Clear(id string) error {
	if _, err := r.client.Del(id).Result(); err != nil {
		return err
	}
	return nil
}

func (r *StoreRedis) Exist(id string) bool {
	row := r.client.Exists(id).Val()
	if row > 0 {
		return true
	}
	r.client.Expire(id, r.expire)
	return false
}

func (r *StoreRedis) Start() error {
	if _, err := r.client.Ping().Result(); err != nil {
		return err
	}
	return nil
}